package com.cn.wanxi.autoconfig.handler;

/**
 * @ClassName GlobalExceptionHandler
 * @Description TODO
 * @Author JiJiang
 * @Date 2023/7/6 17:53
 * @Version 1.0
 */

import com.cn.wanxi.autoconfig.exception.SelfException;
import com.cn.wanxi.autoconfig.vo.ResultVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestControllerAdvice
@Log4j2
//@ResponseBody
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    public ResultVO<String> exceptionHandler(HttpServletRequest request, Exception e) {


        log.error("ip为：{}的客户端访问路径：{}时异常", request.getRemoteAddr(), request.getRequestURL());


        //region
//        //绑定异常是需要明确提示给用户的
//        if (e instanceof BindException) {
//            BindException exception = (BindException) e;
//            List<ObjectError> errors = exception.getAllErrors();
//            String msg = errors.get(0).getDefaultMessage();//获取自错误信息
//            return ResultVO.getResultOnlyMsg("出错了");
//
//        }
//        // 其余异常简单返回为服务器异常
//        return ResultVO.getResultOnlyMsg("出错了");
        //endregion


        String reason, causePoint;
        StackTraceElement stackTraceElement;
        if (e instanceof SelfException) {
            reason = ((SelfException) e).getException().getMessage();
            stackTraceElement = (((SelfException) e).getException()).getStackTrace()[0];

            causePoint = ((SelfException) e).getCasePoint();

            ((SelfException) e).getException().printStackTrace();

        } else {
            causePoint = "";
            reason = e.getMessage();
            stackTraceElement = e.getStackTrace()[0];
            e.printStackTrace();
        }


        int lineNumber = stackTraceElement.getLineNumber();


        String data = "异常位置：" + causePoint + "\t异常原因：" + reason + "\t具体行数为：" + lineNumber;

        return ResultVO.getResult("服务器正在更新！", data);

    }
}
